package main

import (
	"fmt"
	"log"

	"github.com/hashicorp/consul/api"
)

// 删除consul注册的一个服务的所有实例
func main() {
	// 创建一个 Consul 客户端实例
	config := api.DefaultConfig()
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatalf("Failed to create Consul client: %v", err)
	}

	// 初始化一个 Catalog 接口
	catalog := client.Catalog()

	// 指定要删除实例的服务名
	serviceName := "grpc_demo"

	// 获取指定服务名的所有实例
	serviceEntries, _, err := catalog.Service(serviceName, "", nil)
	if err != nil {
		log.Fatalf("Failed to list instances for service %s: %v", serviceName, err)
	}

	// 遍历服务的所有实例，逐个删除
	for _, entry := range serviceEntries {
		err := client.Agent().ServiceDeregister(entry.ServiceID)
		if err != nil {
			log.Printf("Failed to deregister service %s: %v", entry.ServiceID, err)
			continue
		}
		fmt.Printf("Service instance %s deregistered successfully\n", entry.ServiceID)
	}
}
